
package com.aktk.battlenole;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MultiDeviceActivity extends Activity {
    //TextView lMessage;
    //Button bSwitch;
    Button createButton;
    Button joinButton;
    Button generateButton;
    // GameData game;
    String message;

    private boolean gameCreateable = false;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multi_activity_switch);

        createButton = (Button)this.findViewById(R.id.newGameButton);
        createButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
            	generatePressed();
            	new Handler().postDelayed(new Runnable() {
				    @Override
			        public void run() {
				    	createPressed();
			        }
			    }, 5000);
            }

        });
        joinButton = (Button)this.findViewById(R.id.joinGameButton);
        joinButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                joinPressed();
            }
        });

    }

    private void createPressed(){
        if(gameCreateable) {
            GameData.PlayerID = 1; // You are player 1

            startActivity(new Intent(MultiDeviceActivity.this, SetupGameBoardActivity.class));
        } else {

            // TODO: Notify player, that gameID needs to be generated first
        }
    }

    private void joinPressed(){
        ((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Attemping to join Game ID..");
        EditText e = (EditText)findViewById(R.id.gameIdET);
        int joiningGameId = 0;
        try {
            joiningGameId = Integer.valueOf(e.getText().toString());
        } catch (NumberFormatException ex) {
            ((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Invalid Game ID");
            return;
        }
        System.out.println(joiningGameId);
        GameData.gameID = joiningGameId;
        String str = "http://www.newrog.com/battle/check.php?gameID=" + joiningGameId;
        System.out.println("_" + str + "_");
        new WebTask().execute(str, "J");

    }
    
    private void joinComplete(int gameID){
        System.out.println(gameID);
        if(gameID == 0) {
            ((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Unable to Join.  Re-check Game ID.");
            return;
        }
        GameData.PlayerID = 2; // You are player 2
        // if its NOT 0, then it found a game
        startActivity(new Intent(MultiDeviceActivity.this, SetupGameBoardActivity.class));
    }

    private void generatePressed(){
    	((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Generating Game ID");
        Random r = new Random();
        GameData.gameID = Math.abs(r.nextInt(1000000));
        // String str = String.valueOf(GameData.gameID);
        String tempString = "gameID=" + GameData.gameID;
        new WebTask().execute("http://www.newrog.com/battle/check.php?" + tempString, "G");
    }

    // if gameID comes in as 0, then no game was found.
    private void generatedComplete(int gameID){
        if(gameID != 0) {
            ((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Failed, Try again...");
            GameData.gameID = 0;
            gameCreateable = false;
            return;
        }
        gameCreateable = true;
        String str = String.valueOf(GameData.gameID);
        // shows an UNUSED gameID to be given to other player to join this game
        ((TextView)findViewById(R.id.messageLabel_Join_Game)).setText("Game ID: " + str + ".  Initiating game.");
    }
    
    class WebTask extends AsyncTask<String, String, String> {
        boolean CreatingGame;

        @Override
        protected String doInBackground(String... uri){
            CreatingGame = false;
            if(uri[1].charAt(0) == 'G') {
                CreatingGame = true;
            }
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            String responseString = null;
            try {
                response = httpclient.execute(new HttpGet(uri[0]));
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    responseString = out.toString();
                } else {
                    // Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            // parse json data
            int tempGameID = 0;
            try {
                JSONArray jArray = new JSONArray(result);
                // for loop, to always get the 'last' element!
                for(int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    System.out.println(json_data);
                    tempGameID = json_data.getInt("gameID");
                }
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data2 " + e.toString());
            } catch (NullPointerException e) {
                // THIS IS WHAT WE WANT! IN THE INSTANCE
                // MEANS NO GAME EXISTS OF THAT GAMEID!
                Log.e("log_tag", "None found! " + e.toString());
            }
            if(CreatingGame)
                generatedComplete(tempGameID);
            else {
                joinComplete(tempGameID);
            }

        }
    }


}
